<template>
    <FormContainer v-if="showPage" show-right :right-tabs="['优惠券详情页', '优惠券列表页']">
        <el-form label-width="150px" class="pa15 pt20" style="min-width: 660px;">
            <el-form-item label-width="0">
                <ul class="f-d-b" style="width: 100%;">
                    <li class="flex pr20">
                        <span class="pl20 fz14">{{ detail.name }}</span>
                        <el-button class="detail-origin-cn ml15">{{ detail.originCn }}</el-button>
                    </li>
                    <li>
                        <el-button type="primary" @click="newAddCoupon">新增相同</el-button>
                    </li>
                </ul>
            </el-form-item>
            <el-form-item mb10 label="券用途：">{{ couponPurposeLabel[detail.purpose] }}</el-form-item>
            <el-form-item v-if="showFormItem.link" mb10 label="关联：">
                <div v-if="campaignLink.name">
                    <span>{{ campaignLink.name }}</span>
                    <el-text type="primary" ml12 fz12 tag="ins" pointer @click="openBlank">新窗口查看</el-text>
                </div>
                <span v-else>--</span>
            </el-form-item>

            <el-form-item mb15 :label="`${isParkCoupon ? '停车券头图' : '优惠券图'}：`">
                <el-image
                    v-if="detail.head_img"
                    :src="detail.head_img"
                    :preview-src-list="[detail.head_img]"
                    class="detail-image"
                />
            </el-form-item>
            <el-form-item mb10 :label="`${isParkCoupon ? '停车' : '优惠'}券标题：`">{{ detail.name }}</el-form-item>
            <div v-if="isFlashCoupon">
                <el-form-item mb10 label="副标题：">{{ detail.subhead || '--' }}</el-form-item>
                <el-form-item v-if="showFormItem.campaigns" mb10 label="优惠券所属活动：">
                    <span v-if="+detail.purpose === 9">{{ detail.link && detail.link.name ? detail.link.name : '--' }}</span>
                    <span v-else>{{ detail.campaign && detail.campaign.name ? detail.campaign.name : '--' }}</span>
                </el-form-item>
                <el-form-item mb10 label="适用范围：">{{ couponChannelLabel[detail.channel] }}</el-form-item>
            </div>
            <el-form-item mb10 label="券类型：">
                <span>{{ detail.soulePeice }}</span>
                <span v-if="isFlashCoupon" class="pl5">{{ detail.souleType }}</span>
                <span :style="{backgroundImage: mallConfig.themeLinearBg}" class="detail-type fz11 ml10">{{ detail.souleText }}</span>
            </el-form-item>
            <div v-if="isFlashCoupon && +detail.soule === 4">
                <el-form-item mb10 label="使用门槛：">
                    <span v-if="+detail.amount_limit === 1">满 {{ detail.amount_over }} 元可使用 1 张</span>
                    <span v-else>不设限</span>
                </el-form-item>

                <el-form-item mb10 label="单笔订单使用上限：">
                    <div v-if="+detail.use_limit === 1">
                        <span v-if="+detail.channel === 3">线下</span>
                        <span>单笔订单最多使用 {{ detail.use_limit_num }} 张</span>
                        <span v-if="+detail.channel === 3">，线上单笔订单最多使用 1 张</span>
                    </div>
                    <div v-else>
                        <span v-if="+detail.channel === 1">不设限</span>
                        <span v-if="+detail.channel === 3">线下单笔订单不设限，线上单笔订单最多使用 1 张</span>
                    </div>
                </el-form-item>
            </div>
            <el-form-item mb10 label="有效期：">
                <span v-if="detail.start_at">{{ detail.start_at }}至{{ detail.end_at }}</span>
                <span v-else-if="detail.valid_period > 0">领取优惠券后 {{ detail.valid_period }} 天有效</span>
                <span v-else>领取优惠券后当天有效</span>
            </el-form-item>
            <el-form-item v-if="showFormItem.buyLimitDetail" mb10 label="会员领取权限：">
                <ul v-if="+detail.participation_rules === 1">
                    <li v-if="detail.levelText">{{ detail.levelText }}</li>
                    <li v-if="detail.deny_groups && detail.deny_groups.length">
                        <div v-for="row in detail.deny_groups" class="text-nowrap">
                            <span>{{ row.text }}</span>
                            <el-text type="primary" pointer ml20 @click="showExportModel(row)">下载人群包</el-text>
                        </div>
                    </li>
                    <li v-if="detail.premiumExclusiveText">{{ detail.premiumExclusiveText }}</li>
                </ul>
                <span v-else>全部会员可领取</span>
            </el-form-item>
            <el-form-item v-if="showFormItem.receiveRule" mb10 label="是否限领：">
                <span v-if="detail.receive_rule > 0">{{ receiveRulesLabel[detail.receive_rule] }} {{ detail.receive_limit }} 张</span>
                <span v-else>不限领</span>
            </el-form-item>
            <div v-if="isFlashCoupon">
                <el-form-item mb10 label="适用店铺：">
                    <span>{{ showDetailText.shopList }}</span>
                    <el-button v-if="detail.group_ids.length > 1" type="primary" link ml15 @click="showDialogVisiblePreview('shopList')">查看全部</el-button>
                </el-form-item>
                <el-form-item v-if="showAllItems" mb10 label="适用商品：">
                    <span>{{ showDetailText.itemList }}</span>
                    <el-button v-if="detail.item_ids.length > 1" type="primary" link ml15 @click="showDialogVisiblePreview('itemList')">查看全部</el-button>
                </el-form-item>
            </div>
            <el-form-item v-if="showFormItem.sendShop" mb10 label="自定义发券权限：">
                <div v-if="detail.sendable === 1">
                    <span>{{ showDetailText.sendShopList }}</span>
                    <el-button v-if="detail.send_shop_ids.length > 1" type="primary" link ml15 @click="showDialogVisiblePreview('sendShopList')">查看全部</el-button>
                </div>
                <span v-else>关闭</span>
            </el-form-item>
            <el-form-item mb10 label="使用须知：">
                <span class="text-wrap">{{ detail.describe || '--' }}</span>
            </el-form-item>

            <div v-if="isFlashCoupon">
                <el-form-item mb10 label="商品退款设置：">
                    {{ detail.item_refundable === 1 ? (isOnLineCoupon ? '可单件退' : '可退') : '不可退' }}
                </el-form-item>
                <el-form-item v-if="+detail.item_refundable === 1" mb10 label="退券设置：">
                    {{ detail.coupon_refundable === 1 ? '优惠券退回券包' : '优惠券不退回' }}
                </el-form-item>
                <el-form-item mb15 label="优惠券详情图：">
                    <ul v-if="detail.detail_imgs && detail.detail_imgs.length" class="f-c f-warp">
                        <li v-for="(row,i) in detail.detail_imgs" class="mr8">
                            <el-image :src="row" class="detail-image" :preview-src-list="detail.detail_imgs" :initial-index="i"/>
                        </li>
                    </ul>
                    <span v-else>--</span>
                </el-form-item>
                <el-form-item mb10 label="发放方式：">
                    <ul v-if="detail.times?.length && showFormItem.sendWayDetail">
                        <li v-for="row in detail.times">{{ row.start_at }} 至 {{ row.end_at }} 发放 {{ row.num }} 张</li>
                    </ul>
                    <p v-else-if="+detail.num > 0 && detail.timing_unpublished_at">
                        {{ detail.timing_published_at }} 至 {{ detail.timing_unpublished_at }} 发放 {{ detail.num }} 张
                    </p>
                    <span v-else>--</span>
                </el-form-item>
                <el-form-item mb10 label="总发放量：">{{ detail.num > 0 ? detail.num : '--' }} 张</el-form-item>
                <el-form-item v-if="showFormItem.advanceNotice" mb10 label="预热时间：">{{ detail.advanceNotice || '--' }}</el-form-item>
                <el-form-item v-if="isFlashCoupon" mb10 label="优惠补贴比例：">
                    商场补贴 {{ detail.mall_subsidy_rate }}%，店铺补贴 {{ detail.shopSubsidyRate }}%
                </el-form-item>
                <el-form-item mb10 label="备注：">
                    <span class="text-nowrap">{{ detail.remark || '--' }}</span>
                </el-form-item>
            </div>
        </el-form>

        <template #right="{ active }">
            <div class="pv15 f-d-c">
                <el-scrollbar v-if="active === 0" style="width: 300px;height: 600px;background-color: #FFFFFF;">
                    <div>{{ detail.shopLogo }}</div>
                    <div>{{ detail.shopName }}</div>
                    <div>{{ detail.shopAddress }}</div>
                    <div v-for="row in 100" style="color: #141414;">{{ row }}优惠券详情页</div>
                </el-scrollbar>
                <div v-if="active === 1">优惠券列表页</div>
            </div>
        </template>
    </FormContainer>

    <!--导出-->
    <GExportModel ref="ExportModelRef"/>
    <!--选择店铺-->
    <CheckShop ref="ShopModelRef" @change="changeShops"/>
    <!--选择商品-->
    <CheckItem ref="ItemModelRef" @change="changeItems"/>

    <!--弹窗显示-->
    <el-dialog v-model="dialogVisiblePreview" :title="previewTitle" width="300px">
        <el-scrollbar max-height="400px">
            <ul style="padding: 0 10px;">
                <li v-for="row in previewList" class="w240 pv4 ellipsis1">{{ row.name }}</li>
            </ul>
        </el-scrollbar>

        <template #footer>
            <el-button @click="dialogVisiblePreview = false">取消</el-button>
        </template>
    </el-dialog>
</template>

<script setup lang="ts">
    import { ref, computed, onMounted } from "vue";
    import { useRoute, useRouter } from "vue-router";
    import { ElMessage } from "element-plus";

    import FormContainer from "@/components/form/FormContainer.vue";
    import CheckShop from "@/components/checkDialog/CheckShop.vue";// 选择店铺
    import CheckItem from "@/components/checkDialog/CheckItem.vue";// 选择商品

    import { isFlashCouponGroupId, isParkCouponGroupId, isOriginShopCoupon } from "@/utils/globalTypes";
    import { getRestfulMallV2CouponDetailHandler } from "@/assets/api/handler.ts";
    import useLoading from "@/hooks/loading";
    import { CouponPurpose } from "@/filters/data.ts";
    import { getFiltersDictLabel, getFiltersDictParaphrase } from "@/filters/utils.ts";
    import { getShowFormItem } from "@/views/MarketingCenter/CouponManage/FlashCoupon/handler.ts";
    import { CouponTypeHandlerText, FCouponChannelLabel, FCouponTypesLabel, FReceiveRulesLabel } from "@/filters";
    import { _mallStore } from "@/store/config";
    import { TypeFilters } from "@/interface/filters.ts";
    import { getApiShopDetail } from "@/assets/api";
    import { getLotteryPeriodText } from "@/utils/time.ts";
    import { getBuyLimitDetail, getBuyLimitPreview } from "@/components/formUtils/BuyLimit.ts";

    const { showLoading, hideLoading } = useLoading();// 加载loading
    const mallConfig = ref<ObjValueAny>(_mallStore.mallZeusConfig);

    const route = useRoute();
    const router = useRouter();

    const routeParams: ObjValueAny = route.params;// 跳转参数 params
    // 切换券用途 部分字段显示/隐藏
    const showFormItem = computed(() => {
        return getShowFormItem(detail.value);
    });
    // 闪购优惠券
    const isFlashCoupon = computed(() => {
        return +routeParams.group_id === isFlashCouponGroupId;
    });
    // 停车优惠券
    const isParkCoupon = computed(() => {
        return +routeParams.group_id === isParkCouponGroupId;
    });
    // 店铺优惠券
    const isShopCoupon = computed(() => {
        return +routeParams.origin === isOriginShopCoupon;
    })
    // 线上券
    const isOnLineCoupon = computed(() => {
        return detail.value.channel === 2
    });

    const radioPurpose = ref<TypeFilters.filter[]>(CouponPurpose());// 券用途
    const couponPurposeLabel = ref<ObjValueStr>(getFiltersDictLabel(radioPurpose.value));// 券用途
    const radioPurposeParaphrase = ref<ObjValueNum>(getFiltersDictParaphrase(radioPurpose.value));// 券用途
    const couponChannelLabel = ref<ObjValueStr>(FCouponChannelLabel);// 适用范围
    const receiveRulesLabel = ref<ObjValueStr>(FReceiveRulesLabel);// 券类型

    let showPage = ref<boolean>(false);
    onMounted(() => {
        showLoading();
        getDetail();
    })


    let showAllItems = ref<boolean>(false);// 显示 商品选择 (优惠券架)
    let detail = ref<ObjValueAny>({});
    let campaignLink = ref<ObjValueAny>({});
    const getDetail = (): Promise<void> => {
        return new Promise(resolve => {
            getRestfulMallV2CouponDetailHandler(routeParams.id).then(async (resp: ObjValueAny) => {
                if (resp.code === 200) {
                    const { data } = resp;
                    if (data.link) {
                        campaignLink.value = data.link || {};
                    }
                    data.head_img = data.imgs[0];
                    const typeRow = CouponTypeHandlerText(data);
                    data.soulePeice = typeRow.price;
                    if (isFlashCoupon.value) {
                        data.souleType = typeRow.type;
                    }
                    data.souleText = FCouponTypesLabel[data.soule];

                    getBuyLimitDetail(data, '领取');
                    data.levelNamesPreview = getBuyLimitPreview(data, '领取');
                    // 预热时间
                    if (showFormItem.value.advanceNotice) {
                        data.advanceNotice = getLotteryPeriodText(data.advance_notice);
                    }
                    data.shopSubsidyRate = Math.round((100 - data.mall_subsidy_rate) * 100) / 100;
                    detail.value = resp.data;

                    showAllItems.value = data.origin === 2 && data.channel !== 1;
                    const hasGroupIds: boolean = !!data.group_ids?.length;// 是否选择店铺
                    const hasSendShopIds: boolean = !!data.send_shop_ids?.length;// 是否选择权限店铺
                    const hasItemIds: boolean = !!data.item_ids?.length;// 是否选择商品

                    const promiseAllApi: ObjValueAny[] = [];
                    // 店铺券
                    if (isShopCoupon.value) {
                        if (hasGroupIds) {
                            promiseAllApi.push(getShopDetail(data.group_ids[0]));
                        }
                        if (hasItemIds) {
                            promiseAllApi.push(getItemDataList(data.group_ids[0]));
                        }
                    }
                    if (hasGroupIds || hasSendShopIds) {
                        promiseAllApi.push(getShopDataList());
                    }
                    Promise.all(promiseAllApi).then(() => {
                        if (isShopCoupon.value) {
                            if (hasGroupIds) {
                                showDetailText.value.shopList = shopDetail.name || '';
                                getPreviewShopInfo(detail.value, shopDetail);
                            }
                            if (hasSendShopIds) {
                                ShopModelRef.value.refGetModelValue(shopListData, data.send_shop_ids, 'sendShopList');
                            }
                            if (hasItemIds) {
                                ItemModelRef.value.refGetModelValue(itemListData, data.item_ids);
                            } else {
                                detail.value.itemName = '全部商品';
                            }
                        } else {
                            if (hasGroupIds) {
                                ShopModelRef.value.refGetModelValue(shopListData, data.group_ids, 'shopList');
                            }
                            getPreviewShopInfo(detail.value, _mallStore.mallDetailSetting);
                        }
                        showPage.value = true;
                        hideLoading();
                        resolve();
                    })
                } else {
                    ElMessage.error(resp.msg);
                }
            })
        })
    }

    const showDetailText = ref<ObjValueStr>({});
    const changeShops = (ids: number[], text: string, list: ObjValueAny[], key: string) => {
        showDetailText.value[key] = text;
        detail.value[key] = list;
    }
    const changeItems = (ids: number[], text: string, list: ObjValueAny[]) => {
        showDetailText.value.itemList = text;
        detail.value.itemList = list;
    }

    const getPreviewShopInfo = (data: ObjValueAny = {}, row: ObjValueAny = {}) => {
        data.shopLogo = row.logo || '';
        data.shopName = row.name || '';
        data.shopAddress = row.address || '';
    }

    let dialogVisiblePreview = ref<boolean>(false);
    let previewTitle = ref<string>('');
    let previewList = ref<ObjValueAny[]>([]);
    const showDialogVisiblePreview = (key: string) => {
        if (key === 'itemList') {
            previewTitle.value = '全部适用商品';
        }
        if (key === 'shopList') {
            previewTitle.value = '全部适用店铺';
        }
        if (key === 'sendShopList') {
            previewTitle.value = '全部可发券店铺';
        }
        dialogVisiblePreview.value = true;
        previewList.value = detail.value[key];
    }

    // 店铺列表
    const ShopModelRef = ref();// 绑定选择店铺dom ref
    let shopListData: ObjValueAny[] = [];// 店铺列表
    const getShopDataList = async () => {
        shopListData = await ShopModelRef.value.getStoreDataList();
    }
    // 店铺详情
    let shopDetail: ObjValueAny = {};
    const getShopDetail = async (id: number) => {
        const resp: ObjValueAny = await getApiShopDetail({ shop_id: id });
        shopDetail = resp.data;
    }
    // 商品列表
    const ItemModelRef = ref();
    let itemListData: ObjValueAny[] = [];// 店铺列表
    const getItemDataList = async (id: number) => {
        itemListData = await ItemModelRef.value.getStoreDataList({ shop_id: id });
    }

    // 打开新窗口
    const openBlank = () => {
        if (detail.value.purpose === radioPurposeParaphrase.value.youJiaQuanBao) {
            const _isItem: boolean = campaignLink.value.link_type === 'item';
            let _blankPath: string = _isItem ? 'couponPackageDetail' : 'couponPackageGroupDetail';
            let _routerResolve = router.resolve({
                path: _blankPath,
                query: { id: campaignLink.value.id, type: _isItem ? 3 : 2 },
            });
            window.open(_routerResolve.href, '_blank');
        } else if (campaignLink.value.link_type === 'campaign') {
            const routesDict: ObjValueStr = {
                // 1: 'GameDetail',// 幸运扭蛋机
                // 2: 'GameDetail',// 九宫格转盘
                // 3: 'GameDetail',// 颜值抽奖
                4: 'FriendAssistanceDetail',// 好友助力
                5: 'AssistancePrizeDetail',// 助力抽奖
                7: 'InvitingPrizeDetail',// 邀请有礼
                11: 'InteractDetail',// 互动营销宝
                13: 'QuestionnaireDetail',// 问卷调查
            }
            let _routerResolve = router.resolve({
                path: routesDict[campaignLink.value.type] || 'GameDetail',
                query: {
                    id: campaignLink.value.id,
                    type: campaignLink.value.type,
                },
            });
            window.open(_routerResolve.href, '_blank');
        } else {
            // 发券计划详情
            router.push({
                name: 'SendCouponSceneDetail',
                params: { id: detail.value.id },
            })
        }
    }

    const newAddCoupon = () => {
        router.push({
            name: `${isParkCoupon.value ? 'ParkCouponEdit' : 'CouponEdit'}`,
            params: { origin: routeParams.origin, group_id: +routeParams.group_id },
            query: { id: routeParams.id, same: 'same' }
        })
    }

    const ExportModelRef = ref();
    const showExportModel = (row: ObjValueAny) => {
        const exportTitle: string = isParkCoupon.value ? '停车券' : '闪购优惠券';
        const data = {
            name: `${exportTitle}-${detail.value.name}`,
            content: { name: `${exportTitle}领取限制人群包` },
            body: {
                keyword: 'member_group_data',
                member_group_id: row.id
            },
        }
        ExportModelRef.value.exportApi(data);
    }
</script>

<style scoped lang="scss">
    .detail-origin-cn {
        color: var(--el-button-hover-text-color);
        border-color: var(--el-color-primary);
        background-color: transparent;
        outline: none;
        cursor: default;
    }

    .detail-image {
        width: 70px;
        height: 70px;
        margin-top: 6px;
        vertical-align: top;
    }

    .detail-type {
        color: #FFFFFF;
        line-height: 17px;
        padding: 1px 8px;
        border-radius: 10px;
    }
</style>